package com.intellif.mozping;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.Collection;


public class CuratorOperatorDemo {

    public static void main(String[] args) throws InterruptedException {

        CuratorFramework curatorFramework = CuratorClientUtils.getInstance();
        System.out.println("连接成功.........");

        //创建节点
        try {
            String result = curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/curator/curator1/curator11", "123".getBytes());
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //查询
        try {
            Stat stat = new Stat();
            byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/curator");
            System.out.println("查询为：" + new String(bytes) + "-->stat:" + stat);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //更新节点值
        try {
            Stat stat = new Stat();
            stat = curatorFramework.setData().forPath("/curator", "12345".getBytes());
            System.out.println("更新结束：" + stat);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //查询更新后的值
        try {
            Stat stat = new Stat();
            byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/curator");
            System.out.println("更新后查询为：" + new String(bytes) + "-->stat:" + stat);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //删除节点
        try {
            //默认情况下，version为-1
            System.out.println("删除...");
            curatorFramework.delete().deletingChildrenIfNeeded().forPath("/curator");
        } catch (Exception e) {
            e.printStackTrace();
        }


        /**
         * 事务操作（curator独有的）
         */
        try {
            Collection<CuratorTransactionResult> resultCollections =
                    curatorFramework.inTransaction().create().forPath("/demo1", "111".getBytes())
                            .and().setData().forPath("/demo1", "111".getBytes()).and().commit();
            for (CuratorTransactionResult result : resultCollections) {
                System.out.println(result.getForPath() + "->" + result.getType());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
